package com.linkhub.oms.component.trace.config.filter;

import com.linkhub.oms.common.constant.TraceConstant;
import com.linkhub.oms.component.trace.core.QtTraceContext;
import com.linkhub.oms.component.trace.util.MDCUtil;
import lombok.extern.slf4j.Slf4j;

import javax.servlet.Filter;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Description: TraceIdWebFilter
 * @Author: echo
 * @Date: 2022/9/3 22:02
 * @Version: 1.0
 */
@Slf4j
public class TraceWebFilter implements Filter {
    @Override
    public void doFilter(ServletRequest request,
                         ServletResponse response,
                         FilterChain chain) throws IOException, ServletException {
        try {
            MDCUtil.setTraceAndRequestId();
            HttpServletResponse httpResponse = (HttpServletResponse) response;
            httpResponse.addHeader(TraceConstant.REQUEST_LOG_ID, QtTraceContext.getRequestId());
            chain.doFilter(request, response);
        } finally {
            QtTraceContext.remove();
        }

    }

}
